package cors

import (
	"net/http"
	"strings"
	"time"

	"github.com/gin-contrib/cors"
	"github.com/gin-gonic/gin"

	"github.com/super-team/start-kit/configs"
)

func CORS() gin.HandlerFunc {
	cfg := configs.Config.CORS
	var methods []string
	if cfg.AllowMethods == "*" {
		methods = []string{http.MethodGet, http.MethodPost, http.MethodOptions,
			http.MethodHead, http.MethodDelete, http.MethodPut}
	} else {
		methods = strings.Split(cfg.AllowMethods, ",")
	}
	return cors.New(cors.Config{
		AllowOrigins:     strings.Split(cfg.AllowOrigins, ","),
		AllowMethods:     methods,
		AllowHeaders:     strings.Split(cfg.AllowHeaders, ","),
		ExposeHeaders:    strings.Split(cfg.ExposeHeaders, ","),
		AllowCredentials: cfg.AllowCredentials,
		MaxAge:           time.Duration(cfg.MaxAge) * time.Hour,
	})
}
